<template>
  <div class="app-container">
    <div class="header">
      <el-form :inline="true" :model="filter" ref="ruleFormRef">
        <el-form-item label="设备平台" prop="username" v-if="!route.query.roomId">
          <el-select v-model="filter.type_id" placeholder="请选择" clearable>
            <el-option v-for="item in typeArr" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="科室" prop="department_id" v-if="!route.query.roomId" >
          <el-select v-model="query.department_id" placeholder="请选择"  @change="getRoomData">
            <el-option v-for="item in deptList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="房间" prop="room_id" v-if="!route.query.roomId">
          <el-select v-model="filter.room_id" placeholder="请选择" clearable>
            <el-option v-for="item in roomArr" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="在线状态" prop="username" v-if="!route.query.roomId">
          <el-select v-model="filter.status" placeholder="请选择" clearable  style="width:90px">
            <el-option v-for="(item,index) in onlinestatusArr" :key="index" :label="item" :value="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="开启状态" prop="powerstatus" >
          <el-select v-model="filter.powerstatus" placeholder="请选择" clearable style="width:90px">
            <el-option v-for="(item,index) in powerstatusArr" :key="index" :label="item" :value="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="编号" prop="sn" >
          <el-input v-model="filter.sn" placeholder="请输入编号"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name" >
          <el-input v-model="filter.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searChange" :icon="Search">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="footer">
      <div class="util">
        <div style="flex: 1" v-if="checkList && checkList.length > 0">
          <el-space>
            <el-select v-model="platform_id" placeholder="分配平台" clearable>
              <el-option v-for="item in typeArr" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-button type="success" :loading="platLoading" @click="distEquipment">
              <el-icon>
                <HelpFilled />
              </el-icon>
              分配设备
            </el-button>
          </el-space>
        </div>
        <div v-if="auth && auth.exportzip2 && auth.exportzip1">
          <el-button type="primary" @click="exportHandler" >
            <el-icon><DocumentCopy /></el-icon>
            导出检测报告
          </el-button>
        </div>
        <div v-if="route.query.id || (auth && auth.add)">
          <el-button type="primary" @click="importHandler" v-if="auth && auth.import">
            <el-icon>
              <Plus />
            </el-icon>
            批量导入
          </el-button>
          <el-button type="primary" @click="addHandler" v-if="auth && auth.add">
            <el-icon>
              <Plus />
            </el-icon>
            新增设备
          </el-button>
          

          <el-button type="success" @click="router.go(-1)" v-if="route.query.id || route.query.roomId">
            <el-icon>
              <ArrowLeft />
            </el-icon>
            返回
          </el-button>
        </div>
  
      </div>
      <div class="table-inner">
        <el-table class="table" v-loading="loading" row-key="id" :data="list" style="width: 100%" border
          @selection-change="handleSelectionChange">
          <template #empty><el-empty description="暂无数据" /></template>
          <el-table-column type="selection" width="40" align="center" :selectable="selectable" />
          <el-table-column prop="sn" label="设备编号" align="center">
            <template #default="scope">
              <div style="display: flex;align-items: center;justify-content: center;">
                <el-icon size="16" color="#f56c6c" style="cursor: pointer;margin-right: 10px;" @click="jumpPath(`/loss/index?id=${scope.row.id}`)" v-if="scope.row.damaged" >
                  <WarningFilled />
                </el-icon>
                <span>{{ scope.row.sn }}</span>
                <el-popover
                  placement="top-start"
                  title="设备详情"
                  :width="200"
                  trigger="hover"
                >
                  <template #reference>
                    <el-icon :color="'#333'">
                      <View />
                    </el-icon>
                  </template>
                  <template #default>
                  <div
                    class="demo-rich-conent"
                    style="display: flex; gap: 16px; flex-direction: column"
                  >
                    <div>
                      <p>
                        额定功率：<span>{{scope.row.power}}<span style="font-size:10px;color:12px; margin-left:3px">W</span></span>
                      </p>
                      <p>
                        预警功率：<span>{{scope.row.powerthreshold}}<span style="font-size:10px;color:12px; margin-left:3px">W</span></span>
                      </p>
                      <p>
                        实际功率：<span v-if="scope.row.onlinestatus&&scope.row.onlinestatus.power">{{scope.row.onlinestatus.power}}<span style="font-size:10px;color:12px; margin-left:3px">W</span></span><span v-else>-</span>
                      </p>
                      <p>
                        实际电流：<span v-if="scope.row.onlinestatus&&scope.row.onlinestatus.current">{{scope.row.onlinestatus.current}}<span style="font-size:10px;color:12px; margin-left:3px">A</span></span><span v-else>-</span>
                      </p>
                      <p>
                        实际电压：<span v-if="scope.row.onlinestatus&&scope.row.onlinestatus.voltage">{{scope.row.onlinestatus.voltage}}<span style="font-size:10px;color:12px; margin-left:3px">V</span></span><span v-else>-</span>
                      </p>
                      <p>
                        获取时间：<span style="font-size:10px;color:#666">{{scope.row.update_time}}</span>
                      </p>
                      <p>
                        在线时长：{{scope.row.onlinetime}}<span style="font-size:10px;color:#666; margin-left:3px">H</span>
                      </p>
                      <p>
                        启停时段：
                        <span v-if="scope.row.config&&scope.row.config.autoTime">
                            <p v-for="(itema,index) in scope.row.config.autoTime" :key="index" style="font-size:12px;">
                              <div v-if="itema.openTime&&itema.closeTime"><span style="color:green">始:</span>{{itema.openTime}} <span style="font-size:10px;color:red">终:</span>{{itema.closeTime}}</div>
                              <div v-else>-</div>
                            </p>
                        </span>
                        <span v-else>
                          -
                        </span>
                      </p>
                    </div>
                  </div>
                </template>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="设备名称" align="center" />
          <el-table-column prop="room.name" label="所属房间" align="center" />
          <el-table-column prop="status" label="状态" align="center">
            <template #default="scope">
              <el-switch v-model="scope.row.status" inline-prompt active-text="在线" inactive-text="离线" :active-value="1"
                :inactive-value="0" :disabled="auth && !auth.modify" @change="changeStatus(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="设备状态" align="center">
            <template #default="scope">
              <span v-if="scope.row.status == 1 && scope.row.powerstatus == 1">已开启</span>
              <span v-if="scope.row.status == 1 && scope.row.powerstatus == 2">已关闭</span>
              <span v-if="scope.row.status == 1 && !scope.row.powerstatus">未知</span>
              <span v-if="scope.row.status != 1">已离线</span>
            </template>
          </el-table-column>
          <el-table-column prop="update_time" label="更新时间" align="center" width="200">
            <template #default="scope">
              <span>{{ scope.row.update_time }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="operator" label="操作" min-width="280px" align="center">
            <template #default="scope">
              <el-button type="success" size="small" icon="Setting" @click="jumpPath(`/logs/equipLog?id=${scope.row.id}&sn=${scope.row.sn}`)"
                v-if="auth && auth.InfoLog">操作日志</el-button>
              <el-button type="primary" size="small" icon="Edit" @click="editHandler(scope.row)" v-if="auth && auth.edit">
                编辑
              </el-button>
              <el-button type="primary" size="small" icon="Edit" @click="settingHandler(scope.row)" v-if="auth && auth.setting && scope.row.room_id">
                设备配置
              </el-button>
              <el-button @click="del(scope.row)" type="danger" size="small" icon="Delete" v-if="auth && auth.delete">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination v-model:currentPage="query.page" :page-size="query.limit" :total="total" background
          layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <EquiDialog ref="equiDialog" :typeArr="typeArr" @refresh="getList" />
    <EqImportDialog ref="eqimportDialog" :typeArr="typeArr" @refresh="getList" />
    <EquiSettingDialog ref="equiSettingDialog" :typeArr="typeArr" @refresh="getList" />
    <EqExportDialog ref="eqexportDialog" />
  </div>
</template>

<script lang="ts" setup>
import { ElMessageBox, ElMessage, FormInstance, ElNotification } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { onMounted, reactive, ref, watch } from 'vue'
import EquiDialog from './components/EquiDialog.vue'
import EqImportDialog from './components/EqImportDialog.vue'
import EquiSettingDialog from './components/EquiSettingDialog.vue'
import EqExportDialog from './components/EqExportDialog.vue'
import {
  equipInfo,
  deleteEquipInfo,
  editEquipInfo,
  equipment,
  bindplat,
  onlinestatus,
  departmentList,
  roomList
} from '@/api/admin'
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()
const loading = ref(true)
const list = ref()
const total = ref(0)
const deptList = ref()
const roomArr = ref()
const query = reactive({
  page: 1,
  limit: 10,
  filter: '',
  op:{room_id:'=',type_id:'='},
  department_id:''
})
const filter = reactive({
  type_id: '',
  room_id: ''
})
const powerstatusArr = reactive({
  0: '关闭',
  1: '开启'
})
const onlinestatusArr = reactive({
  0: '离线',
  1: '在线'
})
const auth = ref()
const equiDialog = ref()
const equiSettingDialog = ref()
const eqimportDialog = ref()
const eqexportDialog = ref()
const platform_id = ref() //要分配的平台id
const checkList = ref() //要分配的设备
const platLoading = ref(false)
const getList = () => {
  loading.value = true
  equipInfo(query).then((res) => {
    if (res.code == 200) {
      auth.value = res.data.auth
      total.value = res.data.count
      list.value = res.data.data
      // list.value.forEach(async (item) => {
      //   let { equipment_status, onlineuptime } = await getOnlinestatus(item.id)
      //   item.equipment_status = equipment_status
      //   item.onlineuptime = onlineuptime
      // })
      getTypeList()
    }
    loading.value = false
  })
}
//上级部门列表
const getDeptList = () => {
  departmentList({
    selectFields: 'id,name',
  }).then((res) => {
    if (res.code == 200) {
      deptList.value = res.data
    }
  })
}
const getOnlinestatus = (id) => {
  return new Promise((resolve, reject) => {
    onlinestatus({
      id: id,
    }).then((res) => {
      if (res.code == 200) {
        resolve(res.data)
      }
    })
  })
}
const getRoomData = ()=>{
  roomArr.value = [];
  filter.room_id = '';
  roomList({
    filter:'{"department_id":'+query.department_id+'}',
    selectFields: 'id,name',
  }).then((res) => {
    if (res.code == 200) {
      roomArr.value = res.data
    }
  })
}
const typeArr = ref()
const getTypeList = () => {
  if(auth && auth.value.add && auth.value.edit){
    equipment({ selectFields: 'id,name' }).then((res) => {
    if (res.code == 200) {
      typeArr.value = res.data
    }
  })
  }

}
const searChange = () => {
  let filterObj=JSON.parse(JSON.stringify(filter))
  Object.keys(filterObj).forEach((key) => {
    if(filterObj[key]=="") delete filterObj[key]
  })
  query.filter = JSON.stringify(filterObj)
  query.page = 1
  getList()
}

const onSubmit = () => { }

const reset = () => {
  filter.type_id = ''
  searChange()
}

const addHandler = () => {
  equiDialog.value.show()
}
const importHandler = () => {
  eqimportDialog.value.show()
}
const exportHandler = () => {
  eqexportDialog.value.show()
}


const editHandler = (row) => {
  equiDialog.value.show(row)
}
const settingHandler = (row) => {
  equiSettingDialog.value.show(row)
}
const del = (row) => {
  ElMessageBox.confirm(`你确定要删除设备 “${row.name}” 吗?`, '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    deleteEquipInfo({
      id: row.id,
    }).then((res) => {
      if (res.code == 200) {
        ElNotification({
          title: res.data,
          message: res.msg,
          type: 'success',
        })
        getList()
      }
    })
  })
}
const handleSizeChange = (val: number) => {
  query.page = 1
  query.limit = val
  getList()
}

const handleCurrentChange = (val: number) => {
  query.page = val
  getList()
}

const changeStatus = (row) => {
  ElMessageBox.confirm(
    `确定要${!row.status ? '离线' : '在线'}设备 "${row.name}" 吗？`,
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      editEquipInfo({
        id: row.id,
        status: row.status,
      }).then((res) => {
        if (res.code == 200) {
          ElNotification({
            title: `${!row.status ? '离线' : '在线'}成功`,
            message: res.msg,
            type: 'success',
          })
        } else {
          if (row.status == 0) row.status = 1
          else if (row.status == 1) row.status = 0
        }
      })
    })
    .catch(() => {
      if (row.status == 0) row.status = 1
      else if (row.status == 1) row.status = 0
    })
}
const selectable = (row, index) => {
  if (row.platform_id) return false
  else return true
}
const handleSelectionChange = (val) => {
  checkList.value = val
}
const distEquipment = () => {
  if (!platform_id.value) {
    ElMessage.warning('请选择要分配的平台！')
    return
  }
  let ids = []
  checkList.value.forEach((item) => {
    ids.push(item.id)
  })
  platLoading.value = true
  bindplat({ id: ids, platform_id: platform_id.value }).then((res) => {
    if (res.code == 200) {
      ElNotification({
        title: `分配成功`,
        message: res.msg,
        type: 'success',
      })
      platform_id.value = ''
      getList()
    }
    platLoading.value = false
  })
}

const jumpPath = (url) => {
  router.push(url)
}

watch(route, () => {
  routerWatch()
})
const routerWatch=()=>{
  if (route.query.id) {
    filter.type_id = Number(route.query.id)
  }else{
    filter.type_id = ""
  }
  query.filter = JSON.stringify(filter)
  if (route.query.roomId) {
    filter.room_id = Number(route.query.roomId)
  }else{
    filter.room_id = ""
  }
  query.filter = JSON.stringify(filter)
}
routerWatch()
getList()
getDeptList();
</script>

<style scoped lang="scss">
@import '../index';
</style>
